<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class GrowthNumberLog extends Model
{
    protected $table = "c_growth_number_log";

    public function taskhall()
    {
        return $this->hasOne('App\Models\TaskHall', 'id', 'task_id');
    }
    
    /**
     * @param $data
     * @param $task_id
     * @return bool
     * 添加成长值记录
     */
    public static function add($data, $task_id)
    {
        $info = TaskHall::where([['id', '=', $task_id],'states'=>1])->first();
        if(empty($info)){
            return false;
        }
        $task = new self();
        $task->date_at = date("Y-m-d H:i:s", time());;
        $task->task_id = $task_id;
        $task->work_id = $data['work_id'];
        if(isset($data['api']) && $data['api'] ==1){ //如果接口请求,完成分享
            $task->type = 0;
        }else{
            $task->type = isset($data['type'])?$data['type']:0;
        }
        $task->number = $info->growup_num;
        (new DoctorWorks())->where([['id', '=',$data['work_id']]])->increment("growth_value", $info->growup_num);
        TaskHall::growthValueInformation($data);//设置工作室等级类型
        //查看任务是否完成
        $com = TaskComplete::where(['work_id'=>$data['work_id'],'task_id'=>$task_id])->first();
        if(empty($com)){
            TaskComplete::add($data,$task_id);
        }
        return $task->save();
    }

    /**
     * @param $filter
     * 获取成长值列表
     */
    public static function getList($filter)
    {
        $list = self::where([['work_id', '=', $filter['work_id']]])->orderBy("id", "desc")->simplePaginate()->toArray();
        foreach ($list['data'] as $k => &$v) {
            if ($v['type'] == 0) {
                $v['dec'] = null;
                $info = TaskHall::where(['id' => $v['task_id']])->first();
                if ($info) {
                    $v['dec'] = $info->task_name;
                }
            } elseif ($v['type'] == 1) {
                $v['dec'] = "课程订单赠送成长值";
            } elseif ($v['type'] == 2) {
                $v['dec'] = "商品订单赠送成长值";
            } elseif ($v['type'] == 3) {
                $v['dec'] = "咨询订单赠送成长值";
            }
        }
        return $list;
    }

    /**
     * @param $data
     * @return bool
     *消费多少金额,给多少成长值
     */
    public static function giveGrowthNumbers($data)
    {
        if (round($data['number']) >= 1) {
            $task = new self();
            $task->date_at = date("Y-m-d H:i:s", time());;
            $task->task_id = $data['order_id'];
            $task->work_id = $data['work_id'];
            $task->number = $data['number'];
            $task->type = $data['type'];
            (new DoctorWorks())->where([['id', '=',$data['work_id']]])->increment("growth_value", $data['number']);
            return $task->save();
        }
        return true;
    }

    
}
